package com.beardedcoder.lowPower.service;

import java.util.ArrayList;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

public class MyServiceConnector implements ServiceConnection {
	private PowerService mService;
	private Context mCalledFromContext;
	private ArrayList<Runnable> mRunnables = new ArrayList<Runnable>();
	
	public MyServiceConnector(Context app) {
		mCalledFromContext = app.getApplicationContext();
	}
	
	public PowerService getService() {
		return mService;
	}
	
	private boolean isServiceBound() {
		return (mService != null);
	}
	

	@Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        mService = ((PowerService.LocalBinder)service).getService();
        runAnyOutstandingTasks();
    }
    
    @Override
    public void onServiceDisconnected(ComponentName className) {
        mService = null;
    }
    
	public void doBindService() {
		
	    mCalledFromContext.bindService(new Intent(mCalledFromContext, PowerService.class), this, Context.BIND_AUTO_CREATE);
	}

	public void doUnbindService() {
	    if (isServiceBound() && mCalledFromContext != null) {
	        // Detach our existing connection.
	    	mCalledFromContext.unbindService(this);
	    }
	}
	
	public void runWhenConnected(Runnable toRun) {
		
		mRunnables.add(toRun);
		
		// if we're not currently bound to service, exit
		if (! isServiceBound()) return;
		
		runAnyOutstandingTasks();
	}
	
	private void runAnyOutstandingTasks() {		
		while (mRunnables.size() >= 1){
			Runnable run = mRunnables.remove(0);
			Thread t = new Thread(run);
			t.run();
		}
	}
	
	
}
